package com.victor.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.victor.entity.Option;
import com.victor.entity.Question;
import com.victor.service.QuestionnaireService;
import com.victor.utils.Msg;

/**
 * 问卷调查管理
 * 
 * @author Mr.Zhang
 *
 */
@RestController
@RequestMapping("/question")
public class QuestionnaireController {

	@Autowired
	private QuestionnaireService service;
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	// 获取问卷调查列表
	@RequestMapping("/getAll")
	public Msg getAll() {
		List<Question> questions = service.getAll();
		logger.info("获取问卷调查列表");
		return Msg.success().add("questions", questions);
	}

	// 添加问题
	@RequestMapping("/add")
	public Msg add(@RequestBody Question question) {

		if (question == null) {
			return Msg.fail("question无值");
		}
		logger.info(question.toString());

		// 向数据库添加问题(返回id)
		int i = service.addQuestion(question);
		// 向数据库添加选项
		List<Option> options = question.getOptions();
		for (Option option : options) {
			option.setQuestionid(String.valueOf(question.getId()));
		}
		int j = service.addOptions(options);
		return (i > 0 && j > 0) ? Msg.success() : Msg.fail();
	}

	// 修改问卷调查信息
	@RequestMapping("/update")
	public Msg update(@RequestBody Question question) {

		if (question == null) {
			return Msg.fail("question无值");
		}
		logger.info(question.toString());

		// 修改问题
		int i = service.updateQuestion(question);

		// 通过问题id删除所有选项
		service.deleteOption(question.getId());

		// 重新向数据库添加选项
		List<Option> options = question.getOptions();
		for (Option option : options) {
			option.setQuestionid(String.valueOf(question.getId()));
		}
		int j = service.addOptions(options);
		return (i > 0 && j > 0) ? Msg.success() : Msg.fail();
	}

	// 批量删除
	@RequestMapping("/batchDelete")
	public Msg batchDelete(int[] qids) {

		for (int qid : qids) {
			// 删除提问
			service.deleteQuestion(qid);
			// 删除选项
			service.deleteOption(qid);
		}
		return Msg.success();
	}

	// Excel导入
	@RequestMapping("importQuestion")
	public Msg importQuestion(MultipartFile file, String adminid) {
		String result = service.importQuestion(file, adminid);
		if (result.equals("success")) {
			return Msg.success();
		}
		return Msg.fail();
	}

}
